package com.example.school.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.school.dto.UserLoginDto;
import com.example.school.dto.UserTiedStudentDto;
import com.example.school.mapper.StudentMapper;
import com.example.school.pojo.Student;
import com.example.school.pojo.User;
import com.example.school.service.UserService;
import com.example.school.mapper.UserMapper;
import com.example.school.utils.common.enums.*;
import com.example.school.utils.common.result.Result;
import com.example.school.utils.config.BaseContext;
import com.example.school.utils.config.HttpClientUtil;
import com.example.school.utils.config.LoginFailedException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;

/**
* @author 24354
* @description 针对表【user】的数据库操作Service实现
* @createDate 2024-03-16 19:10:30
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Autowired
    private UserMapper userMapper;

    private static final String WX_LOGIN="https://api.weixin.qq.com/sns/jscode2session";

    @Override
    public Result userLogin(UserLoginDto dto) {
        HashMap<String, String> map = new HashMap<>();
        map.put("appid", WeChat.WeChat_Login_token.getAppid());
        map.put("secret",WeChat.WeChat_Login_token.getSecret());
        map.put("js_code",dto.getCode());
        map.put("grant_type", "authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN, map);
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        log.info("openId:{}",openid);
        if (openid==null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        User user = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getOpenId,openid));
        if (user==null) {
            user=User.builder().openId(openid).build();
            boolean adduser = userMapper.adduser(user);
            if (!adduser) {
                throw new LoginFailedException(MessageConstant.UPLOAD_FAILED);
            }
        }
        String id= String.valueOf(user.getUserId());
        String token = Jwts.builder()
                .setHeaderParam(Message.Jwt_Alg, Jwt.User_Jwt_Key.getAlg())
                .setHeaderParam(Message.Jwt_Typ, Jwt.User_Jwt_Key.getTyp())
                .setSubject(Jwt.User_Jwt_Key.getName())
                .setExpiration(new Date(System.currentTimeMillis() + Jwt.User_Jwt_Key.getExp()))
                .claim(Message.User_Id,id )
                .signWith(SignatureAlgorithm.HS256, Jwt.User_Jwt_Key.getKey())
                .compact();
        return Result.okResult(token);
    }

    @Autowired
    private StudentMapper studentMapper;
    @Override
    public Result tiedStudent(UserTiedStudentDto dto) {
        if (dto==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Long userId = BaseContext.getCurrentId();
        User checkUser = userMapper.selectById(userId);
        if (userId==null||checkUser==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        if (checkUser.getStudentNumber()!=null&&
        checkUser.getStudentName()!=null&&
        checkUser.getStudentPhone()!=null&&
        checkUser.getStudentClass()!=null) {
            return Result.errorResult(Code.DATA_EXIST);
        }
        Student checkStudent = studentMapper.selectOne(Wrappers.<Student>lambdaQuery()
                .eq(Student::getStudentNumber, dto.getStudentNumber()));
        if (checkStudent==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        User user=new User();
        user.setUserId(userId);
        user.setStudentName(checkStudent.getStudentName());
        user.setStudentNumber(checkStudent.getStudentNumber());
        user.setStudentPhone(checkStudent.getStudentPhone());
        user.setStudentClass(checkStudent.getStudentClass());
        user.setStudentGrade(checkStudent.getGrade());
        int checkSave = userMapper.updateById(user);
        if (checkSave==0) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result getUser() {
        Long userId = BaseContext.getCurrentId();
        User checkUser = userMapper.selectById(userId);
        if (userId==null||checkUser==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        return Result.okResult(checkUser);
    }
}




